package pub.guoxin.oops.common.sms.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pub.guoxin.oops.common.sms.AliyunProperties;
import pub.guoxin.oops.common.sms.service.SmsFuckService;
import pub.guoxin.oops.common.sms.vo.SmsSend;

@Slf4j
@Service
public class SmsFuckServiceImpl implements SmsFuckService {

    @Autowired
    private AliyunProperties aliyunProperties;


    @Override
    public void send(String mobile, String body) {

        SendSmsRequest request = new SmsSend(mobile, aliyunProperties.getSmsSignName(),
                aliyunProperties.getSmsTemplateCode(), "code", body).buildRequest();

        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = getAcsClient().getAcsResponse(request);
        } catch (ClientException e) {
            log.error("验证码发送错误{}，https://help.aliyun.com/document_detail/55284.html?spm=5176.doc55289.6.556.EHOPEA", e);
        }
        if (!Strings.isNullOrEmpty(sendSmsResponse.getCode()) && "OK".equals(sendSmsResponse.getCode())) {
            log.info("发送短信验证码成功 手机号：{}，验证码：{}", mobile, body);
        } else {
            log.info("发送短信验证码失败 手机号：{}，验证码：{}，Code：{}，Message：{}，https://help.aliyun.com/document_detail/55284.html?spm=5176.doc55289.6.556.EHOPEA", mobile, body,
                    sendSmsResponse.getCode(), sendSmsResponse.getMessage());
        }
    }

    private IAcsClient getAcsClient() throws ClientException {
        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient需要的几个参数
        final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）

        //替换成你的AK
        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliyunProperties.getAccessKeyId(), aliyunProperties.getAccessKeySecret());
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        return new DefaultAcsClient(profile);
    }
}
